//
//  ByRegisterVC.m
//  jinpuyiyuan_ios
//
//  Created by pro on 2017/12/8.
//  Copyright © 2017年 mc. All rights reserved.
//

#import "ByRegisterVC.h"

// api
#import "ByApiUser.h"

// view
#import "ByViewUserOperateCustom.h"

@interface ByRegisterVC ()
@property (nonatomic, strong) UIButton *codeBtn;
@property (nonatomic, strong) ByViewUserOperateCustom *userView;

@property (nonatomic, assign) BOOL isAgree;
@property (nonatomic, copy) NSArray *infoAry;
@property (nonatomic, assign) NSInteger countdownTime;   // 倒计时剩余时间

@end

@implementation ByRegisterVC

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"注册";
    [self addLeftBackBarButtonItem];
    [self createViews];
    self.view.backgroundColor = BY_TABLE_COLOR;
}

#pragma mark - getter
- (NSArray *)infoAry{
    if (!_infoAry) {
        _infoAry = @[@[@"手机号码",@"验证码",@"重置密码",@"确认密码"],@[@"",@"",@"8-24位密码",@"请再次输入登录密码"]];
    }
    return _infoAry;
}

#pragma mark -
- (void)createViews{
    UIView *logoHeaderView = [[UIView alloc] init];
    [self.view addSubview:logoHeaderView];
    [logoHeaderView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(@(0));
        if (@available(iOS 11.0,*)) {
            make.top.equalTo(self.view.mas_safeAreaLayoutGuideTop);
        }else{
            make.top.equalTo(self.view.mas_top);
        }
        make.size.mas_equalTo(CGSizeMake(SCREEN_WIDTH, SCREEN_HEIGHT / 2 - 100));
    }];
    logoHeaderView.backgroundColor = BY_THEME_COLOR;
    
    self.userView = [[ByViewUserOperateCustom alloc] init];
    [self.view addSubview:self.userView];
    NSArray *titles = self.infoAry[0];
    [self.userView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(@(15));
        make.top.equalTo(logoHeaderView.mas_bottom).offset(- 50 - 30);
        make.size.mas_equalTo(CGSizeMake( SCREEN_WIDTH - 30, titles.count * 30 + 100 + 20 * (titles.count - 1)));
    }];
    self.userView.infoAry = self.infoAry;
    // 发送验证码
    __weak typeof(self) weakSelf = self;
    self.userView.sendCodeBlock = ^(UIButton *button) {
        weakSelf.codeBtn = button;
        [weakSelf getcode:weakSelf.codeBtn];
    };
    
    // 协议
    UIButton *selectedButton = [[UIButton alloc] init];
    [self.view addSubview:selectedButton];
    [selectedButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.userView.mas_bottom).offset(10);
        make.size.mas_equalTo(CGSizeMake(20, 20));
        make.left.equalTo(self.userView.mas_left).offset(20);
    }];
    [selectedButton setImage:[UIImage imageNamed:@"Login_selected"] forState:UIControlStateSelected];
    [selectedButton setImage:[UIImage imageNamed:@"Login_unSelected"] forState:UIControlStateNormal];
    selectedButton.selected = YES;
    _isAgree = YES;
    [selectedButton addTarget:self action:@selector(selectAction:) forControlEvents:UIControlEventTouchUpInside];
    
    UILabel *infoLabel = [[UILabel alloc] init];
    [self.view addSubview:infoLabel];
    CGFloat width = [@"我已阅读并同意" getSizeOfString:14].width + 5;
    [infoLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(selectedButton.mas_right).offset(5);
        make.top.equalTo(selectedButton.mas_top);
        make.size.mas_equalTo(CGSizeMake(width, 20));
    }];
    infoLabel.text = @"我已阅读并同意";
    infoLabel.textColor = [UIColor lightGrayColor];
    infoLabel.font = FONT(14);
    
    UILabel *xieyiLabel = [[UILabel alloc] init];
    [self.view addSubview:xieyiLabel];
    NSString *xieyiStr = @"《金普医院服务协议》";
    width = [xieyiStr getSizeOfString:14].width + 5;
    [xieyiLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(infoLabel.mas_right);
        make.size.mas_equalTo(CGSizeMake(width, 20));
        make.top.equalTo(selectedButton.mas_top);
    }];
    xieyiLabel.textColor = [UIColor lightGrayColor];
    NSMutableAttributedString *string = [[NSMutableAttributedString alloc]  initWithString:xieyiStr];
    [string addAttribute:NSForegroundColorAttributeName value:BY_THEME_COLOR range:NSMakeRange(1, xieyiStr.length - 2)];
    xieyiLabel.attributedText = string;
    xieyiLabel.font = FONT(14);
    xieyiLabel.userInteractionEnabled = YES;
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(lookProtocol)];
    [xieyiLabel addGestureRecognizer:tap];
    
    // 注册
    UIButton *registButton = [[UIButton alloc] init];
    [self.view addSubview:registButton];
    [registButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.userView.mas_bottom).offset(70);
        make.left.equalTo(@(40));
        make.size.mas_equalTo(CGSizeMake(SCREEN_WIDTH - 30 - 60, 40));
    }];
    [registButton setTitle:@"立即注册" forState:UIControlStateNormal];
    [registButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    registButton.backgroundColor = BY_THEME_COLOR;
    registButton.titleLabel.font = FONT(14);
    registButton.layer.cornerRadius = 4.0;
    [registButton addTarget:self action:@selector(registAction:) forControlEvents:UIControlEventTouchUpInside];
    
}
#pragma mark - 注册
// 注册
- (void)registAction:(UIButton *)btn{
    UITextField *nameTf = [self.userView viewWithTag:10];
    UITextField *codeTf = [self.userView viewWithTag:11];
    UITextField *passTf = [self.userView viewWithTag:12];
    UITextField *conTf = [self.userView viewWithTag:13];
    ByNetParamsModel *model = [[ByNetParamsModel alloc] init];
    if (nameTf.text.length == 0) {
        [ByCoreToolAlert showOnlyText:@"请输入手机号"];
        return;
    }
    if (codeTf.text.length == 0) {
        [ByCoreToolAlert showOnlyText:@"请输入验证码"];
        return;
    }
    if (passTf.text.length == 0) {
        [ByCoreToolAlert showOnlyText:@"请输入密码"];
        return;
    }
    
    if (conTf.text.length == 0) {
        [ByCoreToolAlert showOnlyText:@"请再次确认密码"];
        return;
    }
    
    if (passTf.text.length < 8  || passTf.text.length > 24) {
        [ByCoreToolAlert showOnlyText:@"密码长度为8-24位"];
        return;
    }
    
    if (![passTf.text isEqualToString:conTf.text]) {
        [ByCoreToolAlert showOnlyText:@"两次输入密码不一致"];
        return;
    }
    
    if (!_isAgree) {
        [ByCoreToolAlert showOnlyText:@"请阅读《金普医院服务协议》"];
        return;
    }
    model.username = nameTf.text;
//    model.code = codeTf.text;
    model.code = @"itboye";
    model.password = passTf.text;
    [self performSelector:@selector(afterLoad:) withObject:@"注册中..." afterDelay:0.01];
    [ByApiUser reigster:model success:^(ByNetBaseResult *result) {
        [ByCoreToolAlert showSuccessWithText:@"注册成功"];
//        NSDictionary *dic = [[NSDictionary alloc] initWithObjectsAndKeys:passTf.text,@"psw",nameTf.text,@"username", nil];
//        [[NSNotificationCenter defaultCenter] postNotificationName:@"registermodel" object:nil userInfo:dic];
//        [self performSelector:@selector(popVC) withObject:nil afterDelay:1];
        [self dismissViewControllerAnimated:YES completion:nil];
    } failure:^(ByNetBaseResult *result) {
        [ByCoreToolAlert showFailureWithText:result.msg];
    }];
    
}

- (void)popVC{
    [self dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark -
- (void)selectAction:(UIButton *)button{
    button.selected = !button.selected;
    _isAgree = button.selected;
}
#pragma mark -- 获取验证码
- (void)getcode:(UIButton *)btn{
    UITextField *nameTF = [self.userView viewWithTag:10];
    if (nameTF.text.length == 0) {
        [ByCoreToolAlert showOnlyText:@"请输入手机号"];
        return;
    }
    
    if (nameTF.text.length != 11) {
        [ByCoreToolAlert showOnlyText:@"请输入正确手机号"];
        return;
    }
    
    ByNetParamsModel *model = [[ByNetParamsModel alloc] init];
    model.mobile = nameTF.text;
    model.type = @"1";
    btn.enabled = NO;
    [self performSelector:@selector(afterLoad:) withObject:@"发送中..." afterDelay:0.01];
    [ByApiUser getCode:model success:^(ByNetBaseResult *result) {
        [ByCoreToolAlert showSuccessWithText:result.data];
        _countdownTime = 60;
        NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(countdownAction:) userInfo:nil repeats:YES];
        [timer fire];
    } failure:^(ByNetBaseResult *result) {
        btn.enabled = YES;
        [ByCoreToolAlert showFailureWithText:result.msg];
    }];
}

- (void)afterLoad:(NSString *)str{
    [ByCoreToolAlert showLoadind:str];
}
#pragma mark -- 倒计时
- (void)countdownAction:(NSTimer *)timer{
    if (_countdownTime > 0) {
        _countdownTime --;
        [self.codeBtn setTitle:[NSString stringWithFormat:@"(%li)重新获取",(long)_countdownTime] forState:UIControlStateNormal];
    }else {
        self.codeBtn.enabled = YES;
        [self.codeBtn setTitle:@"发送验证" forState:UIControlStateNormal];
        [timer invalidate];
    }
}

#pragma mark - 查看协议
- (void)lookProtocol{
    
}

@end
